// pages/register/register.js
import {
  PHONE_SEND_CODE,
  PHONE_VALIDATE,
} from '../../../request/api.js'
import { 
  isValidatePhoneNumber,
 } from "../../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber: '',
    password: '',
    smsCodeTipsMsg: '发送验证码',
    leftTime: 60,
    timeoutNumber: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onUnload: function(){
    if(this.data.timeoutNumber){
      clearTimeout(this.data.timeoutNumber);
    }
  },

  showToast: function(message){
    wx.showToast({
      title: message,
      icon: 'none'
    })
  },

  bindIdInput: function (e) {
    this.data.phoneNumber = e.detail.value;
  },
  bindPasswordInput: function (e) {
    this.data.password = e.detail.value;
  },

  register: function () {
    var phone = this.data.phoneNumber.trim();
    var code = this.data.password.trim();
    if(!phone){
      this.showToast('请输入手机号');
      return;
    } else if(!isValidatePhoneNumber(phone)){
      this.showToast('请输入正确手机号');
      return;
    } else if(!code){
      this.showToast('请输入验证码');
      return;
    }
    PHONE_VALIDATE({
      'phone': phone,
      'code': code,
    }).then(res => {
      if (res.data.code == 1) {
        var token = res.data.result.token;
        wx.navigateTo({
          url: '../register_next/register_next?phoneToken='+token,
        })
      } else {
        this.showTips(res.data.message);
      }
    }).catch(err => {
      
    })
  },

  sendSmsCode: function(){
    var phone = this.data.phoneNumber.trim();
    if(!phone){
      this.showToast('请输入手机号');
      return;
    } else if(!isValidatePhoneNumber(phone)){
      this.showToast('请输入正确手机号');
      return;
    }
    PHONE_SEND_CODE({
      'intent': 1,
      'phone': phone
    }).then(res => {
      this.showTips(res.data.code == 1? '验证码已发送，请留意短信' : res.data.message);
      this.countdownTime();
    }).catch(err => {

    });
  },

  countdownTime: function(){
    this.data.leftTime--;
    this.setData({
      smsCodeTipsMsg: this.data.leftTime == 0? '重新发送' : '重新发送(' + this.data.leftTime + 's)',
    });
    if(this.data.leftTime > 0){
      this.data.timeoutNumber = setTimeout(this.countdownTime, 1000);
    } else {
      clearTimeout(this.data.timeoutNumber);
    }
  },

  showTips: function(msg){
    wx.showToast({
      title: msg,
      icon: 'none'
    });
  }
})